package com.baidu.iit.pvm.runtime;

import com.baidu.iit.pvm.process.ActivityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 当路径跳转到一个单元节点时的处理步奏
 *
 * @ThreadSafe
 * Created by 卫立 on 2014/4/7.
 */
public class AtomicOperationTransitionCreateScope implements AtomicOperation {

    private static Logger logger = LoggerFactory.getLogger(AtomicOperationTransitionCreateScope.class);

    public boolean isAsync(InterpretableExecution execution) {
        ActivityImpl activity = (ActivityImpl) execution.getActivity();
        return activity.isAsync();
    }

    public void execute(InterpretableExecution execution) {
        InterpretableExecution propagatingExecution = null;

        ActivityImpl activity = (ActivityImpl) execution.getActivity();

        if (activity.isScope()) {
            //当activity 是一个单元节点，创建子执行器，同时把父执行器设置为不可用状态
            propagatingExecution = (InterpretableExecution) execution.createExecution();

            propagatingExecution.setActivity(activity);
            //设置跳转的路径
            propagatingExecution.setTransition(execution.getTransition());

            execution.setTransition(null);

            execution.setActivity(null);

            execution.setActive(false);

            if (logger.isDebugEnabled()) {
                logger.debug("create scope: parent {} continues as execution {}", execution, propagatingExecution);
            }
            propagatingExecution.initialize();

        } else {
            propagatingExecution = execution;
        }

        propagatingExecution.performOperation(AtomicOperation.TRANSITION_NOTIFY_LISTENER_START);
    }
}
